﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using HVACWebService.Common;
using HVACWebService.DomainModel.Able;

namespace HVACWebService.Cloud.Able
{
    public class AbleDeviceCloudService
    {
        private string _developerId = ConfigHelper.GetValue<string>("DeveloperId");
        private string _accessKey = ConfigHelper.GetValue<string>("AccessKey");
        private string _majorDomain = ConfigHelper.GetValue<string>("MajorDomain");
        private string _subDomain = ConfigHelper.GetValue<string>("SubDomain");
        private string _ableServiceUrl = ConfigHelper.GetValue<string>("AbleServiceUrl");
        private string _secretKey = ConfigHelper.GetValue<string>("SecretKey");



        /// <summary>
        /// 获取设备在线信息
        /// </summary>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public bool GetAbleOnlineDeviceInfo(string physicalDeviceId)
        {

            var data = "{\"physicalDeviceId\":\"" + physicalDeviceId + "\"}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-bind/v1/isDeviceOnline", data, "isDeviceOnline",
                physicalDeviceId);
            var respDic = returnDate.Contains("true");
            //通过键access_token获取值           
            return respDic;
        }

        /// <summary>
        /// 查询设备是否已经绑定
        /// </summary>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public bool IsDeviceBound(string physicalDeviceId)
        {
            var data = "{\"physicalDeviceId\":" + "\"" + physicalDeviceId + "\"}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-bind/v1/isDeviceBound", data, "isDeviceBound",
                physicalDeviceId);
            return returnDate.Contains("true");
        }


        /// <summary>
        /// 获取用户单台设备详细信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="deviceId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public string GetUserDeviceInfo(string openId, string deviceId, string physicalDeviceId)
        {

            if (string.IsNullOrEmpty(deviceId))
            {
                return GetUserDeviceInfo(openId, physicalDeviceId);
            }

            var ableDevice = new AbleDeviceCloudService();
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                return ableDevice.GetUserDeviceInfo(openId, userId, token, deviceId, physicalDeviceId);
            }
            return "";
        }


        /// <summary>
        /// 获取用户单台设备详细信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public string GetUserDeviceInfo(string openId, string physicalDeviceId)
        {
            var ableDevice = new AbleDeviceCloudService();
            var loginInfo = LoginAble(openId);

            var ableDeviceCloudService = new AbleDeviceCloudService();
            var allDevices = ableDeviceCloudService.GetUserDevices(openId);

            if (allDevices == null)
                return "User Not Device";


            var targetDevice = allDevices.UserAllAbleDevices.FirstOrDefault(d => d.PhysicalDeviceId == physicalDeviceId);
            if (targetDevice != null && !string.IsNullOrEmpty(targetDevice.DeviceId))
            {

                if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
                {
                    var userId = loginInfo["userId"].ToString();
                    var token = loginInfo["token"].ToString();

                    return ableDevice.GetUserDeviceInfo(openId, userId, token, targetDevice.DeviceId, physicalDeviceId);
                }
            }
            else
            {
                return "User Not Device";
            }

            return null;
        }


        /// <summary>
        /// 获取用户设备列表
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public AbleDevicesExtend GetUserDevicesExtend(string openId)
        {
            var loginInfo = LoginAble(openId);
            try
            {
                if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
                {
                    var userId = loginInfo["userId"].ToString();
                    var token = loginInfo["token"].ToString();

                    var returnDate =
                        UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + "/zc-bind/v1/listDevices", "",
                            userId, token, "");
                    var returnObje = JsonSerializer.Instance.Deserialize<AbleDevicesExtend>(returnDate);
                    if (returnObje != null)
                    {
                        returnObje.UserId = userId;
                    }

                    return returnObje;
                }
            }
            catch (Exception)
            {
                return new AbleDevicesExtend();
            }

            return new AbleDevicesExtend();
        }



        public string GetAllAbleDevices(int offset)
        {
            var data = "{\"offset\":" + offset + ",\"limit\":1000}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-bind/v1/getAllDevices", data, "getAllDevices",
                "0003");
            var respDic = JsonSerializer.Instance.Deserialize<AbleUserLogInModel>(returnDate);
            //通过键access_token获取值           

            return "";
        }



        /// <summary>
        ///  打开关闭设备风机
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="isOpen"></param>
        /// <returns></returns>
        public string OpenAndCloseFanReturnStr(string openId, string physicalDeviceId, string deviceId, bool isOpen)
        {
            var url = "";
            if (isOpen)
            {
                url = "/aircleaner/v1/openAirCleaner";
            }
            else
            {
                url = "/aircleaner/v1/closeAirCleaner";
            }

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                var data = "{\"deviceId\":" + deviceId + "}";
                return UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + url, data, userId, token,
                    physicalDeviceId);
            }
            return "";
        }


        /// <summary>
        /// 登陆Able 获取用信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public AbleUserLogInModel LoginAbleGetLoginInfo(string openId)
        {

            var data = "{\"provider\":\"weixin\",\"openId\":\"" + openId + "\"}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-account/v1/loginWithOpenId", data,
                "loginWithOpenId", "");
            var respDic = JsonSerializer.Instance.Deserialize<AbleUserLogInModel>(returnDate);
            //通过键access_token获取值

            return respDic;
        }

        /// <summary>
        /// 获取用户设备列表 返回字符串
        /// </summary>
        /// <param name="openId"></param>
        public AbleDevicesForServiceGetDeviceListModel GetOpenIdDeviceListRetrunStr(string openId)
        {

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();

                var returnDate =
                    UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + "/zc-bind/v1/listDevices", "", userId,
                        token, "");
                return JsonSerializer.Instance.Deserialize<AbleDevicesForServiceGetDeviceListModel>(returnDate);

            }
            return new AbleDevicesForServiceGetDeviceListModel();
        }

        //

        /// <summary>
        /// 获取用户单台设备详细信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="deviceId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="serverUrl"></param>
        /// <param name="ableDeviceAction"></param>
        /// <returns></returns>
        public void SynchronousDataServiceSingleDevice(string openId, string deviceId, string physicalDeviceId,
            string serverUrl, Action<AbleDeviceInfo> ableDeviceAction)
        {

            var httpWebRequestHelp = new HttpWebRequestHelp();
            var url = serverUrl + "/AbleCloudService/api/SingleDeviceData/GetAirQualitySynchronization?openid=" + openId +
                      "&deviceId=" + deviceId + "&physicalDeviceId=" + physicalDeviceId + "&token=QZ3RkTfsx23s3sd2224" +
                      "&testKey=Dev1CeA!r8UrG";
            var returnDate = httpWebRequestHelp.GetData<AbleDeviceInfo>(url);


            ableDeviceAction.Invoke(returnDate);
            //ConfigHelper.HtmlService5Url
        }



        /// <summary>
        /// 获取ShareCode
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public AbleShareCode GetShareCode(string deviceId, string physicalDeviceId, string openId)
        {
            var data = "{\"deviceId\":" + deviceId + ",\"timeout\":86500 }";

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();

                var returnData = UserPostHttp(_ableServiceUrl + "/zc-bind/v1/getShareCode", data, userId, token,
                    physicalDeviceId);
                if (!returnData.Contains("error") || returnData.Contains("3812"))
                {
                    return JsonSerializer.Instance.Deserialize<AbleShareCode>(returnData);
                }

            }
            return null;
        }


        /// <summary>
        /// 查询设备的用户列表
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public AbleThirdPartyUserListModel GetDeviceThirdPartyUserList(string deviceId, string physicalDeviceId)
        {
            var data = "{\"userList\":" + deviceId + "}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-account/v1/getOpenIdsByUserList", data,
                "getOpenIdsByUserList", physicalDeviceId);
            return JsonSerializer.Instance.Deserialize<AbleThirdPartyUserListModel>(returnDate);
        }


        /// <summary>
        /// 查询设备的用户列表
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public AbleDeviceAllUserInfoModel GetDeviceUserList(string deviceId, string physicalDeviceId)
        {
            var data = "{\"deviceId\":" + deviceId + "}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-bind/v1/listUsers ", data, "listUsers",
                physicalDeviceId);
            return JsonSerializer.Instance.Deserialize<AbleDeviceAllUserInfoModel>(returnDate);
        }


        /// <summary>
        ///  打开关闭设备风机
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="isOpen"></param>
        /// <returns></returns>
        public bool OpenAndCloseFan(string userId, string token, string physicalDeviceId, string deviceId, bool isOpen)
        {
            var url = "";
            if (isOpen)
            {
                url = "/aircleaner/v1/openAirCleaner";
            }
            else
            {
                url = "/aircleaner/v1/closeAirCleaner";
            }

            var data = "{\"deviceId\":" + deviceId + "}";
            var returnDate = UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + url, data, userId, token,
                physicalDeviceId);
            return returnDate.Contains("OK");
        }

        /// <summary>
        ///  打开关闭设备风机
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="isOpen"></param>
        /// <returns></returns>
        public bool OpenAndCloseFan(string openId, string physicalDeviceId, string deviceId, bool isOpen)
        {
            var url = "";
            if (isOpen)
            {
                url = "/aircleaner/v1/openAirCleaner";
            }
            else
            {
                url = "/aircleaner/v1/closeAirCleaner";
            }

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                var data = "{\"deviceId\":" + deviceId + "}";
                var returnDate = UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + url, data, userId, token,
                    physicalDeviceId);
                return returnDate.Contains("true");
            }
            return false;
        }


        /// <summary>
        /// 发送数据到设备
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="sendData"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="mesageCode"></param>
        public bool SendToDevice(string userId, string token, string sendData, string physicalDeviceId, string deviceId,
            string mesageCode)
        {

            var returnData =
                UserPostHttp(
                    _ableServiceUrl + "/zc-bind/v1/sendToDevice?deviceId=" + deviceId + "&messageCode=" + mesageCode,
                    sendData, userId, token, physicalDeviceId, "application/octet-stream");
            if (!returnData.Contains("error") || returnData.Contains("3812"))
            {
                //var boundDeviceService = new BoundDeviceDb();
                //boundDeviceService.UpdateBoundDevice(openId, physicalDeviceId, state);

                return true;
            }

            return false;

        }


        /// <summary>
        /// 发送数据到设备
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="sendData"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="mesageCode"></param>
        public byte[] SendToDevice(string openId, string sendData, string physicalDeviceId, string deviceId,
            string mesageCode)
        {
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                var returnData =
                    UserPostHttpSendToDevice(
                        _ableServiceUrl + "/zc-bind/v1/sendToDevice?deviceId=" + deviceId + "&messageCode=" + mesageCode,
                        sendData, userId, token, physicalDeviceId, "application/octet-stream");

                return returnData;

            }
            return new byte[1];
        }



        /// <summary>
        /// 发送数据到设备
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="sendData"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="deviceId"></param>
        /// <param name="mesageCode"></param>
        public string SendToDeviceRetrunMessage(string openId, string sendData, string physicalDeviceId, string deviceId,
            string mesageCode)
        {
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                var returnData =
                    UserPostHttp(
                        _ableServiceUrl + "/zc-bind/v1/sendToDevice?deviceId=" + deviceId + "&messageCode=" + mesageCode,
                        sendData, userId, token, physicalDeviceId, "application/octet-stream");
                return returnData;
            }
            return "";
        }


        /// <summary>
        /// 获取用户单台设备详细信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="deviceId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public string GetUserDeviceInfo(string openId, string userId, string token, string deviceId,
            string physicalDeviceId)
        {
            try
            {
                var returnDate =
                    UserPostHttp(_ableServiceUrl + "/aircleaner/v1/getAirQuality", "{\"deviceId\":" + deviceId + "}",
                        userId, token, physicalDeviceId).Replace("pm2.5", "pm25");
                if (returnDate.Contains("99999"))
                {
                    return returnDate;
                }



                return returnDate;
            }
            catch (Exception)
            {
                return "{\"errorCode\":3807,\"error\":\"\"}";
            }


        }


        /// <summary>
        /// able 设备绑定
        /// </summary>

        /// <param name="physicalDeviceId"></param>
        public bool IsBindDevice(string physicalDeviceId)
        {
            var data = "{\"physicalDeviceId\":" + "\"" + physicalDeviceId + "\"}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-bind/v1/isDeviceBound", data, "isDeviceBound",
                physicalDeviceId);
            return returnDate.Contains("true");
        }

        /// <summary>
        /// able 设备绑定
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="name"></param>
        public AbleDeviceModel BindDevice(string openId, string physicalDeviceId, string name)
        {

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();


                //var data = "{\"deviceId\":" + physicalDeviceId + "}";

                var data = "{\"physicalDeviceId\":\"" + physicalDeviceId + "\",\"name\":\"" + name + "\"}";
                var returnData = UserPostHttp(_ableServiceUrl + "/zc-bind/v1/bindDevice", data, userId, token,
                    physicalDeviceId);
                if (!returnData.Contains("error") || returnData.Contains("3812"))
                {
                    //var boundDeviceService = new BoundDeviceDb();
                    //boundDeviceService.UpdateBoundDevice(openId, physicalDeviceId, state);
                    return JsonSerializer.Instance.Deserialize<AbleDeviceModel>(returnData);
                }
            }
            return null;
        }






        /// <summary>
        /// 解绑 able 设备绑定
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="physicalDeviceId"></param> 
        public bool UnbindDevice(string openId, string physicalDeviceId)
        {
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();

                string deviceId = "";
                var allDevice = GetUserDevices(openId, userId, token);

                if (allDevice == null)
                {
                    return true;
                }

                foreach (var device in allDevice.UserAllAbleDevices)
                {
                    if (physicalDeviceId == device.PhysicalDeviceId)
                        deviceId = device.DeviceId;
                }
                var data = "{\"deviceId\":" + deviceId + "}";
                var returnData = UserPostHttp(_ableServiceUrl + "/zc-bind/v1/unbindDevice", data, userId, token,
                    physicalDeviceId);
                if (!returnData.Contains("error") || returnData.Contains("3812"))
                {
                    //var boundDeviceService = new BoundDeviceDb();
                    //var customerShareInfoService = new CustomerShareInfoDb();
                    //boundDeviceService.UpdateBoundDevice(openId, deviceId, state);
                    //customerShareInfoService.DeleteCustomerShareInfoByBeSharedOpendIdAndPhysicalDeviceId(openId, physicalDeviceId);
                    return true;
                }
            }
            return false;
        }








        /// <summary>
        /// 获取用户设备列表
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public AbleDevices GetUserDevices(string openId, string userId, string token)
        {
            var returnDate = UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + "/zc-bind/v1/listDevices",
                "", userId, token, "");
            return JsonSerializer.Instance.Deserialize<AbleDevices>(returnDate.Replace("devices", "UserAllAbleDevices"));
        }



        /// <summary>
        /// 获取用户设备列表
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public AbleDevices GetUserDevices(string openId)
        {
            var loginInfo = LoginAble(openId);
            try
            {
                if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
                {
                    var userId = loginInfo["userId"].ToString();
                    var token = loginInfo["token"].ToString();

                    var returnDate =
                        UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + "/zc-bind/v1/listDevices", "",
                            userId, token, "");
                    var returnObje =
                        JsonSerializer.Instance.Deserialize<AbleDevices>(returnDate.Replace("devices",
                            "UserAllAbleDevices"));
                    if (returnObje != null)
                    {
                        returnObje.UserId = userId;
                    }

                    return returnObje;
                }
            }
            catch (Exception)
            {
                return new AbleDevices();
            }

            return new AbleDevices();
        }

        /// <summary>
        /// 获取用户设备列表
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public List<AbleDeviceInfoExpand> GetUserDeviceInfos(string openId)
        {
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();
                var returnDate =
                    UserPostHttp(ConfigHelper.GetValue<string>("AbleServiceUrl") + "/zc-bind/v1/listDevices", "", userId,
                        token, "");
                return GetUserDevicesRealtimeInfo(openId, userId, token,
                    JsonSerializer.Instance.Deserialize<AbleDevices>(returnDate.Replace("devices", "UserAllAbleDevices")));
            }
            return null;
        }

        private List<AbleDeviceInfoExpand> GetUserDevicesRealtimeInfo(string openId, string userId, string token,
            AbleDevices ableDevices)
        {
            var ableDeviceService = new AbleDeviceCloudService();

            var ableDeviceInfoExpands = new List<AbleDeviceInfoExpand>();
            foreach (var ableDevice in ableDevices.UserAllAbleDevices)
            {
                var ableDeviceInfoExpand =
                    JsonSerializer.Instance.Deserialize<AbleDeviceInfoExpand>(ableDeviceService.GetUserDeviceInfo(
                        openId, userId, token, ableDevice.DeviceId, ableDevice.PhysicalDeviceId));
                ableDeviceInfoExpand.PhysicalDeviceId = ableDevice.PhysicalDeviceId;
                ableDeviceInfoExpand.name = ableDevice.Name;
                ableDeviceInfoExpands.Add(ableDeviceInfoExpand);
            }

            return ableDeviceInfoExpands;

        }

        /// <summary>
        /// 登陆Able 获取用信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public Dictionary<string, object> LoginAble(string openId)
        {

            var data = "{\"provider\":\"weixin\",\"openId\":\"" + openId + "\"}";
            var returnDate = DeveloperPostHttp(_ableServiceUrl + "/zc-account/v1/loginWithOpenId", data,
                "loginWithOpenId", "");
            JavaScriptSerializer Jss = new JavaScriptSerializer();
            Dictionary<string, object> respDic = (Dictionary<string, object>) Jss.DeserializeObject(returnDate);
            //通过键access_token获取值

            return respDic;
        }

        /// <summary>
        /// 分享码绑定设备
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="shareCode"></param>
        /// <param name="deviceId"></param>
        public bool ShareCodeBindDevice(string openId, string shareCode, string deviceId)
        {
            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();

                var data = "{\"shareCode\":\"" + shareCode + "\"}";
                var returnData = UserPostHttp(_ableServiceUrl + "/zc-bind/v1/bindDeviceWithShareCode", data, userId,
                    token, deviceId);
                if (!returnData.Contains("error") || returnData.Contains("3812"))
                {
                    //var boundDeviceService = new BoundDeviceDb();
                    //var customerShareInfoService = new CustomerShareInfoDb();
                    //boundDeviceService.UpdateBoundDevice(openId, deviceId, state);
                    //customerShareInfoService.DeleteCustomerShareInfoByBeSharedOpendIdAndPhysicalDeviceId(openId, physicalDeviceId);
                    return true;
                }

            }
            return false;
        }

        /// <summary>
        /// 解绑 able 设备绑定
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="deviceId"></param>
        /// <param name="state"></param>
        /// <param name="physicalDeviceId"></param>
        public bool UnbindDevice(string openId, string deviceId, int state, string physicalDeviceId)
        {

            var loginInfo = LoginAble(openId);
            if (loginInfo["userId"] != null && loginInfo["userId"].ToString() != "")
            {
                var userId = loginInfo["userId"].ToString();
                var token = loginInfo["token"].ToString();

                var data = "{\"deviceId\":" + deviceId + "}";
                var returnData = UserPostHttp(_ableServiceUrl + "/zc-bind/v1/unbindDevice", data, userId, token,
                    physicalDeviceId);
                if (!returnData.Contains("error") || returnData.Contains("3812"))
                {
                    //var boundDeviceService = new BoundDeviceDb();
                    //var customerShareInfoService = new CustomerShareInfoDb();
                    //boundDeviceService.UpdateBoundDevice(openId, deviceId, state);
                    //customerShareInfoService.DeleteCustomerShareInfoByBeSharedOpendIdAndPhysicalDeviceId(openId, physicalDeviceId);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        ///  uers post 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="physicalDeviceId"></param>
        /// <returns></returns>
        public string UserPostHttp(string url, string body, string userId, string token, string physicalDeviceId)
        {
            return UserPostHttp(url, body, userId, token, physicalDeviceId, "application/x-zc-object");
        }

        /// <summary>
        ///  uers post 异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="contentType"></param>
        /// <param name="getDatAction"></param>
        /// <returns></returns>
        public void UserPostHttpAsync(string url, string body, string userId, string token, string physicalDeviceId,
            string contentType, Action<string> getDatAction)
        {
            var subDomain = _subDomain;


            var nonce = GenerateRandomString(16);
            var timestamp = DateTimeStamp.DateTimeToStamp(DateTime.Now);
            var timeOut = 60.ToString();


            var signatureStr = timeOut + timestamp + nonce + token;
            var signature = Sha1.Sha1Encrypt(signatureStr);




            HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);


            httpWebRequest.ContentType = contentType; //  "application/x-zc-object";
            httpWebRequest.Headers.Add("X-Zc-Major-Domain", _majorDomain);
            httpWebRequest.Headers.Add("X-Zc-Sub-Domain", subDomain);
            httpWebRequest.Headers.Add("X-Zc-User-Id", userId);


            httpWebRequest.Headers.Add("X-Zc-Timestamp", timestamp.ToString());
            httpWebRequest.Headers.Add("X-Zc-Timeout", timeOut.ToString());
            httpWebRequest.Headers.Add("X-Zc-Nonce", nonce);
            httpWebRequest.Headers.Add("X-Zc-User-Signature", signature);

            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            if (body != "")
            {
                byte[] btBodys = Encoding.UTF8.GetBytes(body);
                httpWebRequest.ContentLength = btBodys.Length;
                httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            }

            try
            {
                httpWebRequest.BeginGetRequestStream(backAction =>
                {
                    var req = (HttpWebRequest) backAction.AsyncState;
                    var response = (HttpWebResponse) req.EndGetResponse(backAction);

                    using (var sw = response.GetResponseStream())
                    {
                        if (sw != null)
                        {
                            using (var reader = new StreamReader(sw))
                            {
                                var returnData = reader.ReadToEnd();

                                getDatAction.Invoke(returnData);
                            }
                        }
                    }
                    response.Close();

                }, httpWebRequest);

            }
            catch (Exception)
            {
                getDatAction.Invoke("{\"errorCode\":99999,\"error\":\"able service error\"}");
                ;
            }

            //httpWebRequest.Headers.Add("Content-Length", httpWebRequest.ContentLength.ToString());


        }

        /// <summary>
        ///  uers post 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public string UserPostHttp(string url, string body, string userId, string token, string physicalDeviceId,
            string contentType)
        {
            var subDomain = _subDomain;


            var nonce = GenerateRandomString(16);
            var timestamp = DateTimeStamp.DateTimeToStamp(DateTime.Now);
            var timeOut = 60.ToString();


            var signatureStr = timeOut + timestamp + nonce + token;
            var signature = Sha1.Sha1Encrypt(signatureStr);




            HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);


            httpWebRequest.ContentType = contentType; //  "application/x-zc-object";
            httpWebRequest.Headers.Add("X-Zc-Major-Domain", _majorDomain);
            httpWebRequest.Headers.Add("X-Zc-Sub-Domain", subDomain);
            httpWebRequest.Headers.Add("X-Zc-User-Id", userId);


            httpWebRequest.Headers.Add("X-Zc-Timestamp", timestamp.ToString());
            httpWebRequest.Headers.Add("X-Zc-Timeout", timeOut.ToString());
            httpWebRequest.Headers.Add("X-Zc-Nonce", nonce);
            httpWebRequest.Headers.Add("X-Zc-User-Signature", signature);

            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            if (body != "")
            {
                byte[] btBodys = Encoding.UTF8.GetBytes(body);

                httpWebRequest.ContentLength = btBodys.Length;
                httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            }



            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();

                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();

                return responseContent;
            }
            catch (Exception e)
            {

                return "{\"errorCode\":99999,\"error\":\"able service error\"}";
            }

            //httpWebRequest.Headers.Add("Content-Length", httpWebRequest.ContentLength.ToString());

        }



        //body是要传递的参数,格式"roleId=1&uid=2"
        //post的cotentType填写:
        //"application/x-www-form-urlencoded"
        //soap填写:"text/xml; charset=utf-8"
        public string DeveloperPostHttp(string url, string body, string methodName, string physicalDeviceId)
        {

            var subDomain = _subDomain;

            var nonce = GenerateRandomString(16);
            var timestamp = DateTimeStamp.DateTimeToStamp(DateTime.Now);
            var timeOut = 7200.ToString();


            var signatureStr = timeOut + timestamp + nonce + _developerId + methodName + _majorDomain + subDomain;
            var signature = GetDeveloperSignature(signatureStr, _secretKey);


            HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

            httpWebRequest.ContentType = "application/x-zc-object";
            httpWebRequest.Headers.Add("X-Zc-Major-Domain", _majorDomain);
            httpWebRequest.Headers.Add("X-Zc-Sub-Domain", subDomain);
            httpWebRequest.Headers.Add("X-Zc-Developer-Id", _developerId);
            httpWebRequest.Headers.Add("X-Zc-Access-Key", _accessKey);


            httpWebRequest.Headers.Add("X-Zc-Timestamp", timestamp.ToString());
            httpWebRequest.Headers.Add("X-Zc-Timeout", timeOut.ToString());
            httpWebRequest.Headers.Add("X-Zc-Nonce", nonce);
            httpWebRequest.Headers.Add("X-Zc-Developer-Signature", signature);

            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            //httpWebRequest.Headers.Add("Content-Length", httpWebRequest.ContentLength.ToString());

            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();

                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();

                return responseContent;
            }
            catch (Exception)
            {

                return "false";
            }


        }


        /// <summary>
        ///  uers post 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="physicalDeviceId"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public byte[] UserPostHttpSendToDevice(string url, string body, string userId, string token,
            string physicalDeviceId, string contentType)
        {
            var subDomain = _subDomain;


            var nonce = GenerateRandomString(16);
            var timestamp = DateTimeStamp.DateTimeToStamp(DateTime.Now);
            var timeOut = 60.ToString();


            var signatureStr = timeOut + timestamp + nonce + token;
            var signature = Sha1.Sha1Encrypt(signatureStr);




            HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);


            httpWebRequest.ContentType = contentType; //  "application/x-zc-object";
            httpWebRequest.Headers.Add("X-Zc-Major-Domain", _majorDomain);
            httpWebRequest.Headers.Add("X-Zc-Sub-Domain", subDomain);
            httpWebRequest.Headers.Add("X-Zc-User-Id", userId);


            httpWebRequest.Headers.Add("X-Zc-Timestamp", timestamp.ToString());
            httpWebRequest.Headers.Add("X-Zc-Timeout", timeOut.ToString());
            httpWebRequest.Headers.Add("X-Zc-Nonce", nonce);
            httpWebRequest.Headers.Add("X-Zc-User-Signature", signature);

            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            try
            {

                if (body != "")
                {
                    // byte[] btBodys = Encoding.UTF8.GetBytes(body);
                    byte[] btBodys = strToToHexByte(body);

                    httpWebRequest.ContentLength = btBodys.Length;
                    httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
                }
            }
            catch (Exception e)
            {
                
                throw;
            }




            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream streamReader = httpWebResponse.GetResponseStream();


                byte[] array;
                using (var ms = new MemoryStream())
                {
                    streamReader.CopyTo(ms);
                    array = ms.ToArray();
                }


                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();


             //string ASCIIstr2 = null;
                //for (int i = 0; i < array.Length; i++)
                //{
                //    int asciicode = (int)(array[i]);
                //    ASCIIstr2 += Convert.ToString(asciicode,16);//字符串ASCIIstr2 为对应的ASCII字符串
                //}



                return array;
            }
            catch (Exception e)
            {

                return  new byte[1];
            }

            //httpWebRequest.Headers.Add("Content-Length", httpWebRequest.ContentLength.ToString());

        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        private string HexStringToString(string hs, Encoding encode)
        {
            //以%分割字符串，并去掉空字符
            string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] b = new byte[chars.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                b[i] = Convert.ToByte(chars[i], 16);
            }
            //按照指定编码将字节数组变为字符串
            return encode.GetString(b);
        }


        private static byte[] strToToHexByte(string hexString)
        {
            //hexString = hexString.Trim();
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }




        //private int DateTimeToStamp(DateTime time)
        //{
        //    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        //    return (int)(time - startTime).TotalSeconds;
        //}

        static Random random = new Random();
        static string GenerateRandomString(int length)
        {
            var chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

            StringBuilder result = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                int index = random.Next(chars.Length);
                result.Append(chars[index]);
            }

            return result.ToString().ToLower();
        }

        private string GetDeveloperSignature(string filename, string password)
        {
            var signature = "";
            var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(password));
            hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(filename));
            foreach (byte test in hmacsha256.Hash)
            {
                signature += test.ToString("X2").ToLower();
            }
            return signature;
        }

        //static public string GetUserSignature(string strSha1In)
        //{
        //    SHA1 sha1 = new SHA1CryptoServiceProvider();
        //    var bytesSha1In = Encoding.Default.GetBytes(strSha1In);
        //    var bytesSha1Out = sha1.ComputeHash(bytesSha1In);
        //    var strSha1Out = BitConverter.ToString(bytesSha1Out);
        //    return strSha1Out.Replace("-", "").ToLower();
        //}

    }

}